<?php
namespace app\branch\model;

use think\Model;
use think\Session;
use \app\common\traits\model\UserOperateCheck;
use \app\common\traits\model\TraitModel;
/**
* 分公司管理员管理
*/
class Managers extends Model
{
    use UserOperateCheck;
    //use TraitModel;
    protected $table = 'branch';
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
    protected static $loginuser = '';
    ///////////////////登陆流程/////////////////////
     
     /**
     * [checkLogin 判断是否已经登陆]
     * @return [type] [description]
     */
    public function checkLogin()
    {

        if ($user_token = cookie('token')) {
             if ($login_user = $this->getUserInfo($user_token)) {
                if (false == session('?manager')) {
                  $this->setUserSession($login_user, true);
                      }
                 }    
            }

        if (session('?manager')) {
            $user_id = $this->getLoginUserInfo('id');
            $login_session_id = $this->getUserInfo($user_id, 'login_session_id');
            if ($login_session_id !== session('manager.login_session_id')){
                self::$loginuser = '';
                $this->logout();
                return false;
            }
        }
        return session('?manager') ? true : false;    
    }

    /**
     * 获取登录用户信息
     * @param  string $field [description]
     * @return [type]        [description]
     */
    public static function getLoginUserInfo($field = '')
    {
        return self::getUserInfo(session('manager.id'), $field);
    }

     /**
     * 获取用户信息
     * @param  array $w [description]
     * @return [type]    [description]
     */
    protected function getUser($account)
    {
        return $this->where('branch_num',$account)->find();
    }
    /**
     * [checkUser 检测账号是否存在]
     * @param  [type] $account [description]
     * @return [type]          [当它返回真值，账号存在]
     */
    public function checkUser($account)
    {
        $result = $this->getUser($account);
        if (empty($result)) {
            return false;
        }
        return true;
    }

     /**
     * [getPassword 判断账号密码是否匹配]
     * @param  [type] $account     [description]
     * @param  [type] $password [description]
     * @return [type]           [当它返回真值，匹配成功]
     */
    public function checkPassword($account,$password)
    {
        $p=$this->getuser($account);
        //手机或者邮箱
        if (!($p['password']==md5($password))){
            return false;
        }
        return true;   

    }

    /**
     * [accountLogin 账号密码方式登录]
     * @param  [type]  $account     [description]
     * @param  [type]  $password    [description]
     * @param  boolean $remember_me [description]
     * @return [type]               [当它返回真值，登陆成功]
     */
    public function accountLogin($account,$password,$remember_me=false)
    {
        $this->clearManagerSession();
        $s = $this->where('branch_num',$account)->value('status');
        if ($s===2) {
            $this->error = lang('你已被锁定');
            return false;
        }
        if ($this->checkOperateCount('managerlogin')) {
            if ($this->checkUser($account)) {
                if ($this->checkPassword($account,$password)) {
                    $this->initOperateCount('managerlogin');
                    $data=$this->getUser($account);
                    //halt($data->data['name']);
                    $this->setUserSession($data, $remember_me);
                    return true;
                }else{
                    //密码错误
                    $this->error = lang('password is error');
                }
            }else{
                //用户不存在
                $this->error = lang('this manager is not empty');
            }
            $this->addOperateCount('managerlogin');
        }else{
            //超限
            $this->error = lang('this manager login fail too many');
        }
        return false;
    }

    /**
     * 退出登录
     * @return [type] [description]
     */
    public function logout()
    {
        $this->clearManagerSession();
        cookie('token', null);
        return true;
    }

    /**
     * [setUserSession 设置用户session信息]
     * @param [type] $data        [对象]
     * @param [type] $remember_me [记住我]
     */
    private function setUserSession($data, $remember_me)
    {
        if ($remember_me == true) {
            cookie('token',$data->id,31536000);
        }
        $login_session_id=session_id();//session_id()
        session('manager.login_session_id',$login_session_id);
        session('manager.id', $data->id);
        session('manager.account', $data->branch_num);
        session('manager.name', $data->data['name']);

    }

    /**
     * [clearManagerSession 清除用户session信息]
     * @return [type] [description]
     */
    private function clearManagerSession()
    {
        session('manager', null);
    }
     /**
     * 根据用户id获取用户信息
     * @param  string $user_id [description]
     * @param  string $field   [description]
     * @return [type]          [description]
     */
    protected static function getUserInfo($user_id, $field = '')
    {
        if (empty($user_id)) {
            return ;
        }
        if (empty(self::$loginuser)) {
            self::$loginuser = self::where('id',$user_id)->find();
        }
        if ($field) {
            if (isset(self::$loginuser[$field])) {
                return self::$loginuser[$field]; 
            }
            return false;
        }
        return self::$loginuser;
    }
    ////////////////////////管理员相关操作////////////////////////////
    /**
     * 创建管理员信息
     * @param  [type] $manager_info_array [description]
     * @return [type]                     [description]
     */
    public function createManager($post_manager_info)
    {
        return $this->create($post_manager_info);
    }
    /**
     * 修改管理员信息
     * @param  [type] $manager_id [description]
     * @param  [type] $info_array [description]
     * @return [type]             [description]
     */
    public function updateManager($manager_id, $post_manager_info)
    {
       return $this->where('id',$manager_id)->update($post_manager_info);
    }
    /**
     * 删除管理员
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    public function delManager($id)
    {
        return $this->where('id',$id)->delete();
    }
    /**
     * [setCardsStatus 设置管理员状态]
     * @param [type] $ids    [description]
     * @param [type] $status [description]
     */
    public function setManagerStatus($ids, $status)
    {
        if (!is_array($ids)) {
            $ids = explode(',', $ids);
        }
        self::where('id', 'in', $ids)->update(['status' => $status]);
        return true;
    }
    /**
     * [getManagerStatus 状态的标示]
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    public function getManagerStatus($value)
    {
        $status = ['0'=>'未锁定', '1'=>'未锁定','2'=>'已锁定'];
        return $status[$value];
    }
    //////////////////////////通知相关操作//////////////////////////

    /**
     * [sendEmail 发送邮箱]
     * @param  [type] $emailAddress [目标邮箱]
     * @param  [type] $theme        [邮件主题]
     * @param  [type] $content      [邮件内容]
     * @return [type]               [description]
     */
    public function sendEmail($emailAddress,$theme,$content)
    {
        $mail = AliyunEmail::init(config('mail'))->send($emailAddress, $theme, $content);
        return $mail;
    }
    /**
     * [sendMobileMessage 发送手机信息]
     * @param  [type] $mobile  [目标手机]
     * @param  [type] $content [内容]
     * @return [type]          [description]
     */
    public function sendMobileMessage($mobile,$content)
    {
       $message = \services\SmsFactory::init('WmSms')->sendMessage($mobile,$content);
       return $message;
    }
    /**
     * [sendNotice 统一通知]
     * @param  [type] $email [description]
     * @param  [type] $phone [description]
     * @return [type]        [description]
     */
    public function sendNotice($email,$phone)
    {
        $content = '账号密码一致:"'.$number.'"自行修改密码';
        //邮箱方式通知
        $a = $this->sendEmail($email,'通知',$content);
        //手机方式通知---模板改动
        $b = $this->sendMobileMessage($phone,$content);
        if( $a&&$b ){
            return  true;
        }
    }


}